package com.z.platform.controller;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Objects;

/**
 * @author 21051
 */
public class ControllerFactory {
    private static Map<String, Controller> allControllerMap = Maps.newHashMap();

    public static Controller getController(String uri) {

        Controller control = allControllerMap.get(uri);
        if (Objects.isNull(control)) {
            synchronized (ControllerFactory.class) {
                if (Objects.isNull(control)) {
                    //初始化controller.xml配置文件将congtroller的path和class路径放到map中
                    ControllersConfig instance = ControllersConfig.getInstance();
                    //根据截取的uri从map中找到对应的class路径
                    String path = instance.getControllersNameByPath(uri);
                    if (null != path) {
                        Class<?> aClass = null;
                        try {
                            aClass = Class.forName(path);
                            Controller controller = (Controller) aClass.newInstance();
                            allControllerMap.put(uri, controller);
                            return controller;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return control;
    }
}
